// 
//  lib.js
//  firefox
//  
//  Created by Zak on 2008-06-12.
//  Copyright 2008 Ant.com. All rights reserved.
// 

top.AntLib =
{
    /**
     * Write something to console logs
     * @param string     The string to write
     */
    toLog: function (str)
    {
        consoleService.logStringMessage("AntLog: " + str);
    },
    
    /**
     * Open the given URL in the current tab
     * @param url       The URL to open
     */
    openURL: function (url)
    {
        window._content.document.location = url;
        window.content.focus();
    },
    
    /**
     * Convert the given terms to a URI-safe string
     * @param terms     The terms to convert
     */
    uriEncode: function (terms)
    {
		return escape(terms).replace(/\//g, "%2F");
    },
    
    /**
     * Open a new window
     * @param windowType    The type of window to be opened
     * @param url           The URL of the page to be loaded
     * @param features      
     */
    openWindow: function (windowType, url, features, params)
    {
        var win = windowType ? wm.getMostRecentWindow(windowType) : null;

        if (win) 
		{
          if ("initWithParams" in win) 
            win.initWithParams(aParams);
          win.focus();
        }    
        else 
		{
          var winFeatures = "resizable,dialog=no,centerscreen" + (features != "" ? ("," + features) : ""); 
          var parentWindow = (this.instantApply || !window.opener || window.opener.closed) ? window : window.opener;

          win = parentWindow.openDialog(url, "_blank", winFeatures, params);
        }    
		
        return win; 
    },

    /**
     * Convert a chrome url to an absolute path
     * @param aPath     The chrome URL
     * @return rv       The path
     */
    chromeToPath: function (aPath) 
    {
        if (!aPath || !(/^chrome:/.test(aPath)))
            return; //not a chrome url
        var rv;
        var ios = CCSV('@mozilla.org/network/io-service;1', "nsIIOService");
        var uri = ios.newURI(aPath, "UTF-8", null);
        var cr = CCSV('@mozilla.org/chrome/chrome-registry;1',"nsIChromeRegistry");

        rv = cr.convertChromeURL(uri).spec;

        if (/^file:/.test(rv))
            rv = this.urlToPath(rv);
        else
            rv = this.urlToPath("file://"+rv);

        return rv;
    },
    
    /**
     * Compare the current FireFox version to the specified one
     * @param versionString     Version string (ex: 1.5)
     * @return boolean          True if at or above the given version, false instead
     */
    compareFFVersion: function (versionString)
    {
        var appInfo = CCSV("@mozilla.org/xre/app-info;1", "nsIXULAppInfo");
        var versionChecker = CCSV("@mozilla.org/xpcom/version-comparator;1", "nsIVersionComparator");
        
        return (versionChecker.compare(appInfo.version, versionString) >= 0);
    },
       
    /**
     * Return the domain without www and .com 
     */
    getSiteName: function (locationObj)
    {
        var hostname = safeGet(locationObj, "hostname");
        var index;
        
        index = hostname.lastIndexOf(".");
        if (index > -1)
            hostname = hostname.substring(0, index);
        index = hostname.lastIndexOf(".");
        if (index > -1)
            hostname = hostname.substring(index + 1);

        return hostname;
    },

    /*
     * return the domain withou subdomains from an string url
     */
     getDomain: function (strURL)
     {
        var domain;
        try
        {
        var ios = CCSV("@mozilla.org/network/io-service;1", "nsIIOService");
        var uri = ios.newURI(strURL, null, null);
        /* // only available on firefox 3
        var eTLDService = CCSV("@mozilla.org/network/effective-tld-service;1", "nsIEffectiveTLDService");
        domain = eTLDService.getBaseDomain(uri);
        */
        var host = uri.host;
        var TLD = host.substring(host.lastIndexOf('.')+1, host.length);
        var hostNoTLD = host.substring(0, host.lastIndexOf('.'));
        var secLevDomain = hostNoTLD.substring(hostNoTLD.lastIndexOf('.')+1, hostNoTLD.length);
        var domain = secLevDomain+'.'+TLD;

        } catch (e) {
                return null;
        }
        return domain;
     },

	/**
	 * Get main browser window, use in order to bypass security context
	 */
	getMainWindow: function ()
	{
		var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIWebNavigation)
                   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                   .rootTreeItem
                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIDOMWindow);

		return mainWindow;
	},

	/*
	 * Return the origin from the filename
	 */
	extractFlvOrigin: function (filename)
	{
		return filename.replace(/\..*/, "");
	},

	/*
	 * Return the flv name from the filename
	 * ex youtube.My_name_video.flv ---> My_name_video
	 */
	extractFlvName: function (filename)
	{
		return filename.replace(/\.flv$/i, "").replace(/^\w+\./i, "")
	},
	
	/*
	 * Extend class inheritance
	 */
	extend: function(subClass, baseClass)
	{
		function inheritance() {}
		inheritance.prototype = baseClass.prototype;
		subClass.prototype = new inheritance();
		subClass.prototype.constructor = subClass;
		subClass.baseConstructor = baseClass;
		subClass.superClass = baseClass.prototype;
	},
	
	/**
	 * Returns "WINNT" on Windows Vista, XP, 2000, and NT systems
	 * "Linux" on GNU/Linux; and "Darwin" on Mac OS X.
	 * @return string The Name of the opertating system
	 */
	getOsName: function ()
	{
		return CCSV("@mozilla.org/xre/app-info;1", "nsIXULRuntime").OS;
	},
	
	/**
     * Converts a number of bytes to the appropriate unit that results in a
     * number that needs fewer than 4 digits
     *
     * NB: The commented part is only available on FF3
     *
     * @param aBytes
     *        Number of bytes to convert
     * @return A pair: [new value with 3 sig. figs., its unit]
     */
    convertByteUnits: function (aBytes)
    {
        var unitIndex = 0;
        var units = ["B", "KB", "MB", "GB"];
        // getStr = CCSV("@mozilla.org/intl/stringbundle;1","nsIStringBundleService").createBundle("chrome://mozapps/locale/downloads/downloads.properties").GetStringFromName;      

        while ((aBytes >= 999.5) && (unitIndex < units.length - 1))
        {
          aBytes /= 1024;
          unitIndex++;
        }
        aBytes = aBytes.toFixed((aBytes > 0) && (aBytes < 100) ? 1 : 0);
        //return [aBytes, getStr(units[unitIndex])];
        return [aBytes, units[unitIndex]];
    },
	
	/*
     * Convert a file url (file:///foo/bar) to an absolute path
     */
    urlToPath : function (aPath)
    {

        if (!aPath || !/^file:/.test(aPath))
          return ;
        var rv;
		var ph = CCIN("@mozilla.org/network/protocol;1?name=file", "nsIFileProtocolHandler");

        rv = ph.getFileFromURLSpec(aPath).path;

        return rv;
    },
    /*
     * Open an file using external protocol service
     */
    openExternal: function (aFile)
    {
       var uri = Cc["@mozilla.org/network/io-service;1"].
                 getService(Ci.nsIIOService).newFileURI(aFile);
     
       var protocolSvc = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
                         getService(Ci.nsIExternalProtocolService);
       protocolSvc.loadUrl(uri);
     
       return;
    },
    /*
     * Fetch a page and return the content in a string
     */
    fetchURL: function (url)
    {
        var ioService = CCSV("@mozilla.org/network/io-service;1", "nsIIOService");
        var uri = ioService.newURI(url, null, null);
        chan = ioService.newChannelFromURI(uri);
        sstream = CCIN("@mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream"); 
        try 
        {
                sstream.init(chan.open()); 
        }
        catch (e) { return null; }
        data = "";
        while (sstream.available())
                data += sstream.read(1024);
        sstream.close();
        return data;
    }
 
}

